package com.linktrip.devicemanager.cmpp;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.linktrip.devicemanager.sms.SMSConfig;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Test {

	public static void main(String[] args) throws Exception {
		int port = 17890;

		new Test().connect(port, "183.230.96.94");
	}

	public void connect(int port, String host) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel arg0) throws Exception {
							arg0.pipeline().addLast(new TimeClientHandler());
						}
					});
			ChannelFuture f = b.connect(host, port).sync();
			f.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}

	public class TimeClientHandler extends ChannelInboundHandlerAdapter {

		private ByteBuf firstMessage;

		public TimeClientHandler() {
//			SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
//			String timeStamp = sdf.format(new Date());

			MsgConnect connect = new MsgConnect();
			connect.setTotalLength(12 + 6 + 16 + 1 + 4);// 消息总长度，级总字节数:4+4+4(消息头)+6+16+1+4(消息主体)
			connect.setCommandId(MsgCommand.CMPP_CONNECT);// 标识创建连接
			connect.setSequenceId(MsgUtils.getSequence());// 序列，由我们指定
			connect.setSourceAddr(SMSConfig.getSpId());// 我们的企业代码
			connect.setAuthenticatorSource(
					MsgUtils.getAuthenticatorSource(SMSConfig.getSpId(), SMSConfig.getSpSharedSecret()));// md5(企业代码+密匙+时间戳)
			connect.setTimestamp(Integer.parseInt(MsgUtils.getTimestamp()));// 时间戳(MMDDHHMMSS)
			connect.setVersion((byte) 0x30);// 版本号 高4bit为3，低4位为0
			byte[] send = connect.toByteArry();

			firstMessage = Unpooled.buffer(send.length);
			firstMessage.writeBytes(send);
		}

		@Override
		public void channelActive(ChannelHandlerContext ctx) throws Exception {
			System.out.println("client channelActive..");
			ctx.writeAndFlush(firstMessage);

			System.out.println();
			SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
			String timeStamp = sdf.format(new Date());
			byte[] b1 = sendShortMsg("|UNLOCK|" + timeStamp + "|", "1064853827150");
			firstMessage = Unpooled.buffer(b1.length);
			firstMessage.writeBytes(b1);
			ctx.writeAndFlush(firstMessage);
			System.out.println("已发送");

		}

		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			System.out.println("client channelRead..");
			ByteBuf buf = (ByteBuf) msg;
			byte[] req = new byte[buf.readableBytes()];
			buf.readBytes(req);
			System.out.println("response:");
			for (byte b : req) {
				String s = Integer.toHexString((b & 0xff));
				System.out.print(((s.length() < 2) ? "0x0" : "0x") + s + ",");
			}
		}

		@Override
		public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
			System.out.println("client exceptionCaught..");
			System.out.println(cause.getMessage());
			ctx.close();
		}
	}

	private static byte[] sendShortMsg(String msg, String cusMsisdn) {
		try {
			int seq = MsgUtils.getSequence();
			MsgSubmit submit = new MsgSubmit();
			submit.setTotalLength(12 + 8 + 1 + 1 + 1 + 1 + 10 + 1 + 32 + 1 + 1 + 1 + 1 + 6 + 2 + 6 + 17 + 17 + 21 + 1
					+ 32 + 1 + 1 + msg.length() + 20);
			submit.setCommandId(MsgCommand.CMPP_SUBMIT);
			submit.setSequenceId(seq);
			submit.setPkTotal((byte) 0x01);
			submit.setPkNumber((byte) 0x01);
			submit.setRegisteredDelivery((byte) 0x01);
			submit.setMsgLevel((byte) 0x01);
			submit.setServiceId("gongbike");
			submit.setFeeUserType((byte) 0x00);
			submit.setFeeTerminalId("");
			submit.setFeeTerminalType((byte) 0x00);
			submit.setTpPId((byte) 0x00);
			submit.setTpUdhi((byte) 0x00);
			submit.setMsgFmt((byte) 0x0f);
			submit.setMsgSrc(SMSConfig.getSpId());
			submit.setSrcId(SMSConfig.getSpCode());
			submit.setDestTerminalId(cusMsisdn);
			submit.setMsgLength((byte) (msg.length()));
			submit.setMsgContent(msg.getBytes("gb2312"));

			// List<byte[]> dataList=new ArrayList<byte[]>();
			// dataList.add(submit.toByteArry());
			// CmppSender sender=new
			// CmppSender(getSocketDOS(),getSocketDIS(),dataList);
			// sender.start();
			System.out.println("发送中...");
			return submit.toByteArry();
		} catch (Exception e) {
			System.out.println("短信发送失败");
			return null;
		}
	}
}